<!--值班表-->
<template>
    <Layout>
        <Form ref="form1" :model="dataToQuery" :label-width="120">
            <Row class="query-form">
                <Col span="8">
                    <FormItem label="单位名称：" prop="order">
                        <company-select v-model="dataToQuery.companyName" style="width:100%" />
                        <!-- <cascader-dom class="query-form-el" ref='queryOrgCascader' @setOrgname='setQueryOrgName'
                                      :orgTree="true"
                                      :setCurrentName="{label:dataToQuery.companyName,value:dataToQuery.companyId}"></cascader-dom> -->
                    </FormItem>
                </Col>
                <Col span="8">
                    <FormItem label='值班年月' >
                        <DatePicker class="query-form-el" placeholder="请选择值班年月" :clearable="false" type="month" v-model='dataToQuery.month'></DatePicker>
                    </FormItem>
                </Col>
                <Col span="8" v-if="!switchFlag">
                    <Button @click="switchQuery(true)" class="ivu-btn-switch" type="text">展开∨</Button>
                    <Button @click="reset1" class="ivu-btn-reset">重置</Button>
                    <Button type="primary" class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
                </Col>
                <Col span="8" v-else>
                    <FormItem label='值班日期' >
                        <DatePicker class="query-form-el" placeholder="请选择值班年月" :clearable="false" v-model='dataToQuery.dateDuty'
                          :options="{disabledDate(date) {return date && dataToQuery.month && renderViewMonth(date) !== renderViewMonth(dataToQuery.month);}}" ></DatePicker>
                    </FormItem>
                </Col>
            </Row>
            <Row v-show="switchFlag" class="query-form">

                <Col span="8" offset="16">
                    <Button @click="switchQuery(false)" class="ivu-btn-switch" type="text">收起∧</Button>
                    <Button @click="reset1" class="ivu-btn-reset">重置</Button>
                    <Button class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
                </Col>
            </Row>
            <Row class="query-form">
                <Col span="24">
                    <Button size="large" class="ivu-btn-add" icon="md-add" @click="addInfo">新增</Button>
                    <download-button :api="exportUrl" :queryForm="dataToQuery" :exportFormBefore="exportBefore" />
                    <Button icon="md-cloud-upload" class="ivu-btn-add" @click="openUpload">导入值班表</Button>
                    <Button icon="md-download" class="ivu-btn-add" @click="downloadModel">下载模板</Button>
                    <!-- <Button type="primary" class="ivu-btn-add" icon="md-cloud-download" @click="exportFormSubmit">导出</Button> -->
                </Col>
            </Row>
        </Form>
        <Table ref='table' :height="tableHeight" no-data-text="没有查询到相关数据!" @on-selection-change='getSelectRows'
               :loading='pageStatus.loading' @on-sort-change="sortChange"
               border :columns="columns1" :data="dataTable">
        </Table>
        <Row style="margin-right:10px;">
            <Col span="24">
                <Page style="float: right" :total="pagedata.total" :page-size="pagedata.pageSize"
                      @on-change="pageChange" @on-page-size-change="pageSizeChange" :page-size-opts="pageSizeArray"
                      show-total show-sizer show-elevator/>
            </Col>
        </Row>
        <Modal :title="this.getModalTitle('值班表')" :transfer=false :mask-closable="false" v-model="dialogShow" v-if="dataToView && dialogShow" :width=800 :styles="{maxHeight:'700px'}" class-name='limit-height-dialog'>
            <Row>
                <Col span="24">
                    <Form ref="dialogForm" :class="mode === 'view'?'modal-view-detail':''" :show-message="false" :model="dataToView" :rules="mode === 'view'?{}:ruleCustom" :label-width="mode === 'view'?160:null" :label-position="mode === 'view'?'right':'top'">
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <!-- <Col span="11">
                                <FormItem label='所属二级集团：' prop='belongOrgId'>
                                    <div v-if="mode === 'view'">{{ dataToView.belongOrgName }}</div>
                                    <Select v-else class='query-form-el' placeholder="集团名称"  v-model='dataToView.belongOrgId' label-in-value @on-change="belongChange">
                                        <Option v-for="item in twoLevel" :value="item.orgId" :key="item.orgId">{{item.orgName}}</Option>
                                    </Select>
                                </FormItem>
                            </Col> -->
                            <Col span="11">
                                <FormItem label='单位名称：' prop='companyId'>
                                    <div v-if="mode === 'view'">{{ dataToView.companyName }}</div>
                                    <div v-else>
                                        <cascader-dom  v-if="show"  class='query-form-el' ref='orgCascader' @setOrgInfo='setCompanyId' @setOrgname="setCompanyName" :orgTree="true"
                                                       :currentOrgId="dataToView.companyId" :rootOrgId="dataToView.belongOrgId"
                                                       :setCurrentName="{label:dataToView.companyName,value:dataToView.companyId}" ></cascader-dom>
                                    </div>
                                </FormItem>
                            </Col>
                            <Col span="11">
                                <FormItem label='三级单位名称:' prop='thirdLevelUnit'>
                                    <div v-if="mode === 'view'">{{ dataToView.thirdLevelUnit }}</div>
                                    <Input v-else class='query-form-el' placeholder="请填写三级单位名称" type='text'
                                           v-model='dataToView.thirdLevelUnit'></Input>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11">
                                <FormItem label='项目部名称：' prop='projectName'>
                                    <div v-if="mode === 'view'">{{ dataToView.projectName }}</div>
                                    <Input v-else class='query-form-el' placeholder="请填写项目部名称" type='text'
                                           v-model='dataToView.projectName'></Input>
                                </FormItem>
                            </Col>
                            <Col span="11">
                                <FormItem label='值班日期：' prop='dateDuty'>
                                    <div v-if="mode === 'view'">{{ renderViewDate(dataToView.dateDuty) }}</div>
                                    <DatePicker v-else class="query-form-el" placeholder="请选择值班年月" v-model='dataToView.dateDuty'></DatePicker>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11">
                                <FormItem label='带班领导：' prop='leaderClass'>
                                    <div v-if="mode === 'view'">{{ dataToView.leaderClass }}</div>
                                    <Input v-else class='query-form-el' placeholder="请填写带班领导" type='text'
                                           v-model='dataToView.leaderClass'></Input>
                                </FormItem>
                            </Col>
                            <Col span="11">
                                <FormItem label='带班领导联系电话' prop='leaderPhone'>
                                    <div v-if="mode === 'view'">{{ dataToView.leaderPhone }}</div>
                                    <Input v-else class='query-form-el' placeholder="请填写带班领导联系电话" type='text'
                                           v-model='dataToView.leaderPhone'></Input>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11">
                                <FormItem label='值班人员(中层领导)：' prop='dutyOfficer'>
                                    <div v-if="mode === 'view'">{{ dataToView.dutyOfficer }}</div>
                                    <Input v-else class='query-form-el' placeholder="请填写值班人员(中层领导)" type='text'
                                           v-model='dataToView.dutyOfficer'></Input>
                                </FormItem>
                            </Col>
                            <Col span="11">
                                <FormItem label='值班人员联系电话：' prop='officerPhone'>
                                    <div v-if="mode === 'view'">{{ dataToView.officerPhone }}</div>
                                    <Input v-else class='query-form-el' placeholder="请填写值班人员联系电话" type='text'
                                           v-model='dataToView.officerPhone'></Input>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11">
                                <FormItem label='填报人：' prop='createUserName'>
                                    <div v-if="mode === 'view'">{{ dataToView.createUserName }}</div>
                                    <Input v-else class='query-form-el' placeholder="请填写填报人" type='text'
                                           readonly v-model='dataToView.createUserName'></Input>
                                </FormItem>
                            </Col>
                            <Col span="11">
                                <FormItem label='填报时间：' prop='createDate'>
                                    <div v-if="mode === 'view'">{{ renderViewDate(dataToView.createDate) }}</div>
                                    <DatePicker v-else class="query-form-el" placeholder="请选择填报时间"
                                                readonly v-model='dataToView.createDate'></DatePicker>
                                </FormItem>
                            </Col>
                        </Row>
                    </Form>
                </Col>
            </Row>
            <div slot="footer">
                <Button v-if="mode != 'view'" type="primary" class='ivu-btn-save' @click="submit('dialogForm')">确定
                </Button>
                <Button v-if="mode != 'view'" type="primary" class='ivu-btn-cancel' @click="handleCancel">取消</Button>
                <Button v-if="mode === 'view'" class='ivu-btn-save' @click="dialogShow=false">关闭</Button>
            </div>
        </Modal>

        <Modal :transfer=false title="批量导入" v-model="modal9" width="800">
            <Form ref="uploadItemData">
                <Row>
                    <i-col span="24">
                        <FormItem label='单位名称：' prop='companyId'>
                            <cascader-dom v-if="modal9" class='query-form-el' ref='orgCascader2' @setOrgInfo='setCompanyId2' @setOrgname="setCompanyName2" :orgTree="true"
                                          :currentOrgId="uploadMap.companyId"
                                          :setCurrentName="{label:uploadMap.companyName,value:uploadMap.companyId}" ></cascader-dom>
                        </FormItem>
                    </i-col>
                </Row>
                <Row>
                    <i-col span="24">
                        <Upload
                                name="file"
                                type="drag"
                                :format="['xlsx', 'xls']"
                                accept=".xlsx, .xls"
                                :before-upload="handleUpload "
                                action="//jsonplaceholder.typicode.com/posts/">
                            <div style="padding: 20px 0">
                                <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
                                <p>请上传xls、xlsx格式的文件</p>
                            </div>
                        </Upload>
                    </i-col>
                </Row>
                <div v-if="fileTrue">
                    <a>{{ uploadMap.file.name }}</a>
                    <Button type="text" icon="md-trash" @click="uploadMap.file = {},fileTrue = false" style="margin-left: 5px;margin-bottom: 3px"/>
                </div>
            </Form>
            <div slot="footer">
                <Button class='ivu-btn-save' @click="submitFile()">上传</Button>
                <Button @click="modal9 = false" class="ivu-btn-cancel" >取消</Button>
            </div>
        </Modal>
        <Modal :transfer=false title="异常数据，请检查模板" v-model="modal10" width="800">
            <!-- <div :style="{height: divHeight, overflowY: 'auto', overflowX: 'hidden'}"> -->
                <Table ref='table3' border :columns="errorColumns" style="margin-top: 0px"
                       :data="errorInfos" width="100%" :height="500" highlight-row stripe size="small"></Table>
            <!-- </div> -->
            <div slot="footer">
                <Button class='ivu-btn-cancel' @click="modal10=false;errorInfos=[]">取消</Button>
            </div>
        </Modal>
    </Layout>
</template>

<script>
    import {Api} from '@/api/index.js'
    import {formatDate} from '@/tools/index'
    var cascaderDom = () => import('@/components/cascader-dom.vue');
    import pageCommonFunction from '@/components/pageCommonFunction.js'
    import {sessionStorage, cookie} from '@/common/cacheUtils.js';

    export default {
        components: {cascaderDom},
        data() {
            return {
                ...this.createCommonDataField(),
                imgUrl: "",
                columns1: [
                    {key: 'dateDuty', title: '值班日期', align: 'center', sortable: "custom", minWidth: 120, render: this.renderCellDate},
                    // {title: '序号', width: 70, fixed: 'left', align: 'center', render: this.indexColumnsRender},
                    // { key:'belongOrgName',title: '所属二级集团',  align: 'center', minWidth: 120, },
                    { key:'companyName',title: '单位名称',  align: 'center', minWidth: 120, },
                    // {key: 'thirdLevelUnit', title: '三级单位名称', align: 'center', minWidth: 120,},
                    // {key: 'projectName', title: '项目部名称', align: 'center', minWidth: 120,},
                    {key: 'leaderClass', title: '带班领导', align: 'center', minWidth: 120,tooltip:true},
                    {key: 'leaderPhone', title: '带班领导联系电话', align: 'center', minWidth: 120,},
                    
                    {key: 'dutyOfficer', title: '值班人员(中层领导)', align: 'center', minWidth: 120,},
                    {key: 'officerPhone', title: '值班人员联系电话', align: 'center', minWidth: 120,},
                    // {key: 'createUserName', title: '填报人', align: 'center', minWidth: 120,},
                    {key: 'createDate', title: '填报时间', align: 'center', sortable: "custom", minWidth: 120, render: this.renderCellDate},
                    this.getActionColumns(),
                ],
                ruleCustom: {
                    belongOrgId: [ { required: true, message: '请填写所属二级集团', trigger: 'change',}],
                    companyId: [ { required: true, message: '请填写单位名称', trigger: 'change',}],
                    // thirdLevelUnit: [{required: true, message: '请填写三级单位名称', trigger: 'change',}],
                    // projectName: [{required: true, message: '请填写项目部名称', trigger: 'change',}],
                    dateDuty: [{required: true, message: '请选择值班日期', trigger: 'change', type: 'date'}],
                    leaderClass: [{required: true, message: '请填写带班领导', trigger: 'change',}],
                    leaderPhone: [{required: true, message: '请填写带班领导联系电话', trigger: 'change',}],
                    dutyOfficer: [{required: true, message: '请填写值班人员(中层领导)', trigger: 'change',}],
                    officerPhone: [{required: true, message: '请填写值班人员联系电话', trigger: 'change',}],
                    createDate: [{required: true, message: '请填写填报时间', trigger: 'change', type: 'date'}],
                },
                tableHeight: 10,
                // api
                queryUrl: Api.queryEnTable.replace('{{table}}', 'dutySchedule'),
                exportUrl: Api.exportEnTable.replace('{{table}}', 'dutySchedule'),
                deleteUrl: Api.deleteEnTable.replace('{{table}}', 'dutySchedule'),
                getUrl: Api.getEnTable.replace('{{table}}', 'dutySchedule'),
                updateUrl: Api.updateEnTable.replace('{{table}}', 'dutySchedule'),
                saveUrl: Api.saveEnTable.replace('{{table}}', 'dutySchedule'),
                // uploadUrl: Api.uploadEnTable.replace('{{table}}', 'dutySchedule'),
                show:true,
                currentUser: JSON.parse(sessionStorage('userId').get('userId')),
                pagedata: {
                    total: 0,
                    pageSize: 50,
                    currentPage: 1,
                },

                uploadMap:{},
                modal9: false,
                modal10: false,
                fileTrue: false,
                errorInfos: [],
                errorColumns: [
                    { key:'index',title: '序号', width: 70, align: 'center'},
                    // { key:'belongOrgName',title: '所属二级集团',  align: 'center', minWidth: 120, },
                    // { key:'companyName',title: '单位名称',  align: 'center', minWidth: 120, },
                    {key: 'thirdLevelUnit', title: '三级单位名称', align: 'center', minWidth: 120,},
                    {key: 'projectName', title: '项目部名称', align: 'center', minWidth: 120,},
                    {key: 'dateDuty', title: '值班日期', align: 'center', minWidth: 120, render: this.renderCellDate},
                    {key: 'leaderClass', title: '带班领导', align: 'center', minWidth: 120,tooltip:true},
                    {key: 'leaderPhone', title: '带班领导联系电话', align: 'center', minWidth: 120,},
                    {key: 'dutyOfficer', title: '值班人员(中层领导)', align: 'center', minWidth: 120,},
                    {key: 'officerPhone', title: '值班人员联系电话', align: 'center', minWidth: 120,},
                ],
               
            }
        },
        async mounted() {
            this.dataToQuery.dynamicSort = 'dateDuty asc'
            this.dataToQuery.monthDuty = this.renderViewMonth(new Date())
            this.dataToQuery.month = new Date()
            this.setTableHeight();
            // this.selectSecGroupNames()
            this.query();
        },
        methods: {
            ...pageCommonFunction,

            setCompanyId2(data) {
                if (data && data instanceof Array && data.length > 0) {
                    this.$set(this.uploadMap, 'companyId', data[data.length - 1])
                }
            },
            setCompanyName2(data) {
                if (data) {
                    this.uploadMap.companyName = data;
                }
            },
            openUpload(){
                this.fileTrue = false
                this.uploadMap = {
                    companyId:this.currentUser.companyId,
                    companyName:this.currentUser.companyName,
                }
                this.modal9 = true;
            },
            handleUpload (file) {
                this.uploadMap.file = file;
                this.fileTrue = true;
                return false;
            },
            submitFile(){
                let formData = new FormData();
                formData.append("file", this.uploadMap.file);
                formData.append("companyId", this.uploadMap.companyId);
                formData.append("createUserId", this.currentUser.userId);
                formData.append("createOrgId", this.currentUser.orgInfo.orgId);
                this.$http.post(this.queryUrl + '/upload', formData).then((res) => {
                    if(res.data.status == 201){
                        this.$Message.error(res.data.msg);
                        this.modal10 = true;
                        let title = ['dateDuty','leaderClass','leaderPhone','dutyOfficer','officerPhone']
                        res.data.data.map((i=>{
                            let cellClassName = {}
                            for (let k in title) {
                                if (['leaderPhone','officerPhone'].includes(title[k])) {
                                    var pattern = /^1[23456789]\d{9}$/
                                    if (!pattern.test(i[title[k]])) {
                                        cellClassName[title[k]] = "table-info-cell-red";
                                    }
                                } else if (i[title[k]] == null){
                                    cellClassName[title[k]] = "table-info-cell-red";
                                }
                            }
                            i.cellClassName = cellClassName;
                        }));
                        this.errorInfos = res.data.data;
                    }else if(res.data.status == 200){
                        this.$Message.success("批量导入成功");
                        /* let dataItems = res.data.data
                         dataItems.forEach(item =>{
                             this.dataToView.items.push(item);
                         })*/
                        this.modal9 = false;
                        this.fileTrue = false
                        this.query()
                    }
                }).catch(e => {
                    console.log(e)
                    this.$Message.error("导入失败！请检查导入文档的格式是否正确");
                })
            },
            downloadModel(){
                this.$http.get(this.queryUrl + '/upload/model',{
                    params: {},
                    responseType: 'arraybuffer'
                }).then((res) => {
                    const aLink = document.createElement("a");
                    let blob = new Blob([res.data], {
                        type: "application/vnd.ms-excel"
                    })
                    aLink.href = URL.createObjectURL(blob);
                    aLink.download = "值班表导入模板.xlsx" //标题
                    aLink.click();
                    document.body.appendChild(aLink);
                })
            },


            selectSecGroupNames(){
                this.$http.get(Api.quqeryTwoOrgInfo).then(res => {
                    this.twoLevel=res.data.data
                }).catch(e => {
                })
            },
            belongChange(value) {
                this.$set(this.dataToView,'belongOrgId',value.value)
                this.$set(this.dataToView,'belongOrgName',value.label)
                this.dataToView.companyId = null
                this.dataToView.companyName = null
                this.$refs.orgCascader.resetCurrentOrg();
                this.show = false;
                setTimeout(() => {
                    this.show = true
                }, 0)
            },
            exportBefore(data){
                if(data.month && data.month instanceof Date) {
                    data.monthDuty = this.renderViewMonth(data.month)
                }
                if(data.dateDuty && data.dateDuty instanceof Date) {
                    data.dateDuty = this.renderViewDate(data.dateDuty)
                }
            },
            deleteData(params) {
                this.deleteDateAjax(params);
            },
            reset1() {
                this.dataToQuery = {};
                this.dataToQuery.dynamicSort = 'dateDuty asc'
                // this.dataToQuery.monthDuty = this.renderViewMonth(new Date())
                // this.dataToQuery.month = new Date()
                // if (this.$refs.queryOrgCascader) {
                //     this.$refs.queryOrgCascader.resetCurrentOrg();
                // }
                
                this.pagedata.currentPage = 1
                this.query()
            },
            query() {
                if(this.dataToQuery.month && this.dataToQuery.month instanceof Date) {
                    this.dataToQuery.monthDuty = this.renderViewMonth(this.dataToQuery.month)
                }
                if(this.dataToQuery.dateDuty && this.dataToQuery.dateDuty instanceof Date) {
                    this.dataToQuery.dateDuty = this.renderViewDate(this.dataToQuery.dateDuty)
                }
                // this.dataToQuery.orgId = this.currentUser.companyId;
                this.queryAjax();
            },

            submit(name) {
                this.submitAjax(name);
            },
            createEmptyDataToAdd() {
                return {
                    createDate: new Date(),
                    createUserId: this.currentUser.userId,
                    createUserName:this.currentUser.userName,
                    id:this.get_uuid(),
                    idFiles:[],
                }
            },
            // async afterDataToViewInit() {
            //     await this.getFiles('id');
            // },
        },
        watch: {},
    }
</script>

<style lang='css' scoped>
    .ivu-form-item {
        padding-right: 20px;
    }

    .query-form-el, .ivu-date-picker, .ivu-input-wrapper {
        width: 100%;
    }

</style>

